Page({
  data: {
    addressList: []
  },
  onShow() {
    const addressList = wx.getStorageSync('addressList') || [];
    this.setData({ addressList });
  },
  addAddress() {
    wx.navigateTo({ url: '/pages/address-edit/address-edit' });
  },
  editAddress(e) {
    const index = e.currentTarget.dataset.index;
    wx.navigateTo({ url: `/pages/address-edit/address-edit?index=${index}` });
  },
  deleteAddress(e) {
    const index = e.currentTarget.dataset.index;
    wx.showModal({
      title: '提示',
      content: '确定要删除该地址吗？',
      success: (res) => {
        if (res.confirm) {
          const addressList = this.data.addressList;
          const isDefault = addressList[index].isDefault;
          addressList.splice(index, 1);
          
          if (isDefault && addressList.length > 0) {
            addressList[0].isDefault = true;
          }
          
          wx.setStorageSync('addressList', addressList);
          this.setData({ addressList });
          wx.showToast({ title: '删除成功', icon: 'success' });
        }
      }
    });
  },
  setDefaultAddress(e) { 
    const index = e.currentTarget.dataset.index;
    const addressList = this.data.addressList.map((item, i) => {
      item.isDefault = i === index;
      return item;
    });
    wx.setStorageSync('addressList', addressList);
    this.setData({ addressList });
    wx.showToast({ title: '设置成功', icon: 'success' });

    // 获取页面栈
    const pages = getCurrentPages();
    if (pages.length > 1) {
      const prevPage = pages[pages.length - 2];
      // 检查是否从确认订单页进入
      if (prevPage.route === 'pages/confirmOrder/confirmOrder') {
        const selectedAddress = addressList.find(item => item.isDefault);
        prevPage.setData({ selectedAddress });
        wx.navigateBack();
      }
    }
  }
});